import { jwtVerify, SignJWT } from 'jose';

const encodedKey = new TextEncoder().encode(process.env.AUTH_SECRET);

export const getToken = (req) => {
    return req.cookies.get('token')?.value;
};

export const verifyToken = async (token) => {
    if (!token) return null;

    try {
        const { payload } = await jwtVerify(token, encodedKey);
        return payload;
    } catch (error) {
        console.error('Token verification failed:', error);
        return null;
    }
};

export const createToken = async (payload) => {
    const token = await new SignJWT(payload)
        .setProtectedHeader({ alg: 'HS256' })
        .setExpirationTime('1d')
        .sign(encodedKey);
    return token;
};
